import express, { Request, Response, NextFunction, ErrorRequestHandler } from 'express';
import { config } from './config';
import { AppDataSource } from './config/database';
import authRouter from './api/auth.route';
import cors from 'cors';
import cron from 'node-cron';
import { refreshAllTokens } from './utils/tokenRefresher';
import deviceRoute from "./api/device.route";
import notifyRouter from './api/notify.route';
import sseRoute from "./api/sse.route";
import sensorRoute from "./api/sensor.route";
import  sceneRoute from  "./api/scene.route";
import './utils/sensor-sampling/sensorSampler';

import authMockRoute from "./mock/api-mock/authMock.route";
import deviceMockRoute from "./mock/api-mock/deviceMock.route";
import { initControlCapability } from './init/initControlCapability';
import subscribeMockRoute from './mock/api-mock/subscribeMock.route';


const app = express();


// 初始化数据库连接
AppDataSource.initialize().then(async () => {
    console.log('数据库连接成功');
    // 初始化设备属性表
    await initControlCapability();

}).catch((error) => {
    console.error('数据库连接失败:', error);
    throw error;
  });


// 配置中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors()); // 跨域支持



// 测试路由
app.get('/', (req, res) => {
  res.send('ecoHeavn service running.');
});

// 授权路由
app.use('/auth', authRouter);
// 设备路由
app.use('/devices', deviceRoute);
// 第三方消息接收
app.use('/api', notifyRouter);
// sse
app.use('/', sseRoute);
// 传感器
app.use('/api', sensorRoute);
// 场景
app.use('/', sceneRoute);


// 第三方api模拟
app.use('/mockapi/auth', authMockRoute);
app.use('/', deviceMockRoute);
app.use('/', subscribeMockRoute);


// 启动服务器
app.listen(config.port, () => {
  console.log(`Server listening on port ${config.port}`);
});


// 每日凌晨2点刷新一次现有token
cron.schedule('0 14 * * *', async () => {
   console.log('[CRON] start refresh all the access_tokens');
   await refreshAllTokens();
});


// // 全局错误处理中间件
// app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
//   console.error(err.stack); // 将错误堆栈信息输出到控制台
//   res.status(500).json({
//     status: 'error',
//     message: 'Internal server error'
//   });
// });












